// @ts-ignore
import axios, {AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig} from 'axios';
import {ElMessage} from 'element-plus';
import router from '../router/index';

const service:AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 20000
});

service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // @ts-ignore
        config.headers['token'] = localStorage.getItem('token');
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    async (response: AxiosResponse) => {
        console.log(response);
        const code = response.data.code;
        console.log("service.interceptors.response", response);
        if (response.status === 200) {
            if (code === 200) {
                return response.data;
            } else {
                if (code == 101 || code == 102) {
                    localStorage.clear();
                    ElMessage.warning(response.data.message + "，请重新登录");
                    console.log("router", router);
                    await router.push("/login");
                } else {
                    console.log("response.data.message", response.data.message)
                    ElMessage.error(response.data.message);
                }
                return Promise.reject();
            }
        } else {
            ElMessage.error("服务器繁忙，请稍后重试");
            return Promise.reject();
        }
    },
    (error: AxiosError) => {
        ElMessage.error("服务器繁忙，请稍后重试");
        return Promise.reject();
    },
);

export default service;
